package adcp.activities;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;

import java.util.ArrayList;
import java.util.List;

import adcp.network.beans.AdcpUpLoad;
import adcp.network.beans.GateDownLoad;
import adcp.network.http.SendAdcp;
import adcp.views.adapter.GateAdapter;
import managers.DatabaseManager;
import managers.UIHandler;
import managers.UserInfo;
import model.OwnUser;
import utils.TimeUtil;

/**
 * ADCP录入界面
 * Created by nimi on 2015/10/27.
 */
public class AdcpActivity extends UIHandler.BaseActivity implements SendAdcp.Delegate {
    private Button back;
    private Button confirm;//确认键
    private Spinner spinner;
    private EditText liuliang;
    private EditText water_level;
    private String time;//当按下确认键时需要同时记录当前时间
    private static List<GateDownLoad> adcps;//当前需要显示的所有adcp信息

    private GateAdapter qudaoAdapter;//传输该用户所对应的渠道信息
    private static AdcpUpLoad adcp = new AdcpUpLoad();//记录需要上传的adcp信息
    private SendAdcp send = new SendAdcp();

    {
        send.setDelegate(this);
    }

    //    private SQLiteHelper dbHelper;
    private static final int liuliang_DECIMAL_DIGITS = 2;
    private static final int water_level_DECIMAL_DIGITS = 3;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_adcp);
//        dbHelper = new SQLiteHelper(this, "im.db", null, 12);
        init();
        //初始化控件

        confirm = (Button) findViewById(R.id.check);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OwnUser ownUser = MyApplication.getOwnUser();
                if (!ownUser.getUser_Role().equals(UserInfo.USEROPER_MOD02)) {
                    Toast.makeText(AdcpActivity.this, "对不起,您的权限不够", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (check()) {
                    new AlertDialog.Builder(AdcpActivity.this).setTitle("ADCP数据上传").
                            setMessage("填写完毕，确认上传？").setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            dataupload();//数据上传
                            //AdcpActivity.this.finish();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            //清空数据
                            liuliang.setText("");
                            water_level.setText("");
                            dialog.dismiss();
                        }

                    }).show();
                    TimeUtil time1 = new TimeUtil();
                    time = time1.currentTime();
                    adcp.setTime(time);
                }
            }
        });
        spinner = (Spinner) findViewById(R.id.qudao_choose);
        spinner.setAdapter(qudaoAdapter);//设置spinner的数据来源
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View arg1, int position,
                                       long arg3) {
                GateDownLoad adcpUpLoad = qudaoAdapter.getItem(position);
                adcp.setId(adcpUpLoad.getStadia_code());
                adcp.setName(adcpUpLoad.getGate_name());
                adcp.setMethod('p');
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                String sInfo = "什么也没选！";
                Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();
            }
        });
        liuliang = (EditText) findViewById(R.id.edit_liuliang);
        InputFilter lengthfilter1 = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                if ("".equals(source.toString())) {
                    return null;
                }
                String dValue = dest.toString();
                String[] splitArray = dValue.split("\\.");
                if (splitArray.length > 1) {
                    String dotValue = splitArray[1];
                    int diff = dotValue.length() + 1 - liuliang_DECIMAL_DIGITS;
                    if (diff > 0) {
                        return source.subSequence(start, end - diff);
                    }
                } else {
                    String sIntegValue = splitArray[0];
                    int diff = sIntegValue.length() - 7;
                    if (diff > 0) {
                        return source.subSequence(start, end - diff);
                    }
                }
                return null;
            }
        };
        InputFilter lengthfilter2 = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                if ("".equals(source.toString())) {
                    return null;
                }
                String dValue = dest.toString();
                String[] splitArray = dValue.split("\\.");
                if (splitArray.length > 1) {
                    String dotValue = splitArray[1];
                    int diff = dotValue.length() + 1 - water_level_DECIMAL_DIGITS;
                    if (diff > 0) {
                        return source.subSequence(start, end - diff);
                    }
                } else {
                    String sIntegValue = splitArray[0];
                    int diff = sIntegValue.length() - 9;
                    if (diff > 0) {
                        return source.subSequence(start, end - diff);
                    }
                }
                return null;
            }
        };
        liuliang.setFilters(new InputFilter[]{lengthfilter1});
        water_level = (EditText) findViewById(R.id.edit_waterlevel);
        water_level.setFilters(new InputFilter[]{lengthfilter2});


    }

    private void init() {
        adcps = new ArrayList<GateDownLoad>();


        SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
        db.beginTransaction();

        try {

            Cursor cursor = db.rawQuery("select t.* FROM t_IrrBAWaterGate as t order by t.orderNum asc", new String[]{});
            while (cursor.moveToNext()) {
                GateDownLoad gate = new GateDownLoad();
                gate.setGate_num(cursor.getString(cursor.getColumnIndex("watergateCode")));//水闸编号
                gate.setGate_name(cursor.getString(cursor.getColumnIndex("watergateName")));//水闸名称
                gate.setGate_hole(cursor.getFloat(cursor.getColumnIndex("watergateNUM")));//水闸孔数
                gate.setStadia_code(cursor.getString(cursor.getColumnIndex("stadiaCode")));//测站编码
                String gatestatus = (cursor.getString(cursor.getColumnIndex("watergateStatus")));
                gate.setGate_state(gatestatus.charAt(0));//水闸状态

                if (gate.getGate_num().startsWith("00000")) {
                    continue;
                }
                adcps.add(gate);

            }
            cursor.close();
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
            DatabaseManager.getInstance().closeDatabase();
        }
        qudaoAdapter = new GateAdapter(this, adcps);
    }

    private boolean check() {
        if (TextUtils.isEmpty(liuliang.getText().toString())) {
            Toast.makeText(this, "流量没有填写！",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(water_level.getText().toString())) {
            Toast.makeText(this, "水位量没有填写！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    public void dataupload() {//上传数据的封装
        adcp.setRate(Float.parseFloat(liuliang.getText().toString()));
        adcp.setWater_level(Float.parseFloat(water_level.getText().toString()));
        send.send(adcp);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    public void onResponse(String s, SendAdcp sendAdcp) {
//        Toast.makeText(this,"上传完成！",Toast.LENGTH_LONG).show();

    }

    public void onError(VolleyError volleyError, SendAdcp sendAdcp) {
        Toast.makeText(this, "网络问题，请重新上传", Toast.LENGTH_SHORT).show();

    }


}
